﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using Aspose.Diagram;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Slides;
using Aspose.Tasks;
using Aspose.Words;
using Aspose.Cells;
using LoadFormat = Aspose.Cells.LoadFormat;
using LoadOptions = Aspose.Slides.LoadOptions;

namespace IceCS.AsposeProd.Lic
{
    /// <summary>
    /// Aspose工具操作
    /// </summary>
    public class AsposeUtil
    {
        private static bool _isImage = false;
        private static bool _isPsd = false;
        private static bool _isCheckPdf = false;
        private static bool _isCheckWord = false;
        private static bool _isCheckExcel = false;
        private static bool _isCheckPpt = false;
        private static bool _isEmail = false;
        private static bool _isTasks = false;
        private static bool _isDiagram = false;
        private static bool _isCAD = false;

        private static string licName = "Aspose.Total.NET.lic";

        /// <summary>
        /// 验证Image
        /// </summary>
        public static void CheckImageLic()
        {
            try
            {
                if (_isImage) { return; }
                var lic = new Aspose.Imaging.License();
                lic.SetLicense(licName);
                _isImage = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 验证Image
        /// </summary>
        public static void CheckPsdLic()
        {
            try
            {
                if (_isPsd) { return; }
                var lic = new Aspose.PSD.License();
                lic.SetLicense(licName);
                _isPsd = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 验证PDF lic
        /// </summary>
        public static void CheckPdfLic()
        {
            try
            {
                if (_isCheckPdf) { return; }
                var lic = new Aspose.Pdf.License();
                lic.SetLicense(licName);
                _isCheckPdf = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 验证Word lic
        /// </summary>
        public static void CheckWordLic()
        {
            try
            {
                if (_isCheckWord) { return; }
                var lic = new Aspose.Words.License();
                lic.SetLicense(licName);
                _isCheckWord = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 验证Excel lic
        /// </summary>
        public static void CheckExcelLic()
        {
            try
            {
                if (_isCheckExcel) { return; }
                var lic = new Aspose.Cells.License();
                lic.SetLicense(licName);
                _isCheckExcel = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 验证Ppt lic
        /// </summary>
        public static void CheckPptLic()
        {
            try
            {
                if (_isCheckPpt) { return; }
                var lic = new Aspose.Slides.License();
                lic.SetLicense(licName);
                _isCheckPpt = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 验证Email lic
        /// </summary>
        public static void CheckEmailLic()
        {
            try
            {
                if (_isEmail) { return; }
                var lic = new Aspose.Email.License();
                lic.SetLicense(licName);
                _isEmail = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// cad lic
        /// </summary>
        public static void CheckCadLic()
        {
            try
            {
                if (_isCAD) { return; }
                var lic = new Aspose.CAD.License();
                lic.SetLicense(licName);
                _isCAD = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 验证Tasks lic
        /// </summary>
        public static void CheckTasksLic()
        {
            try
            {
                if (_isTasks)
                {
                    return;
                }
                var lic = new Aspose.Tasks.License();
                lic.SetLicense(licName);
                _isTasks = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 验证Diagram lic
        /// </summary>
        public static void CheckDiagramLic()
        {
            try
            {
                if (_isDiagram) return;
                var lic = new Aspose.Diagram.License();
                lic.SetLicense(licName);
                _isDiagram = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool IsEncrypted(string pdfFilePath)
        {
            CheckPdfLic();
            var pdf = new Aspose.Pdf.Document(pdfFilePath);
            return pdf.IsEncrypted;
        }

        /// <summary>
        /// 开始解密
        /// </summary>
        /// <param name="pdfFilePath">Pdf文件路径</param>
        /// <param name="isEncrypted">原文件是否加密文件</param>
        /// <param name="error">错误信息</param>
        /// <param name="pageCount">页总数</param>
        /// <returns>是否解密成功</returns>
        public static bool Decrypt(string pdfFilePath, ref bool isEncrypted, out Exception error, out int pageCount)
        {
            CheckPdfLic();
            error = null;
            pageCount = 0;
            try
            {
                var pdf = new Aspose.Pdf.Document(pdfFilePath);
                isEncrypted = pdf.IsEncrypted;
                pageCount = pdf.Pages.Count;
                //如果是加密文件先解密
                if (isEncrypted)
                {
                    pdf.Decrypt();
                    pdf.Save(pdfFilePath);
                    return true;
                }
            }
            catch (Exception ex)
            {
                error = ex;
            }
            return false;
        }

        public static void SplitPdf(int pageNum, int count, string pdfFilePath, string outPdfFilePath, int splitNum)
        {
            CheckPdfLic();
            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfFilePath);
            Aspose.Pdf.Page page;
            Aspose.Pdf.Document newDocument = new Aspose.Pdf.Document();
            try
            {
                if (splitNum > 1)
                {
                    for (int i = pageNum; i < pageNum + splitNum; i++)
                    {
                        newDocument = new Aspose.Pdf.Document();
                        for (int p = i; p <= pdfDocument.Pages.Count; p++)
                        {
                            page = pdfDocument.Pages[p];
                            if (p >= i && p < i + count)
                            {
                                newDocument.Pages.Add(page);
                            }
                            else if (p > i + count)
                            {
                                break;
                            }
                        }
                        newDocument.Save(string.Format(outPdfFilePath, i));
                    }

                }
                else
                {
                    for (int p = 1; p <= pdfDocument.Pages.Count; p++)
                    {
                        page = pdfDocument.Pages[p];
                        if (p >= pageNum && p < pageNum + count)
                        {
                            newDocument.Pages.Add(page);
                        }
                        else if (p > pageNum + count)
                        {
                            break;
                        }
                    }
                    newDocument.Save(outPdfFilePath);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                pdfDocument.Dispose();
                pdfDocument.Dispose();
                newDocument.Dispose();
                newDocument.Dispose();
            }

        }


        /// <summary>
        /// Word转成Pdf文件
        /// </summary>
        /// <param name="src">源文件</param>
        /// <param name="dest">转档文件</param>
        public static void WordConvertToPdf(string src, string dest)
        {
            try
            {
                CheckWordLic();
                // open word file
                var doc = new Aspose.Words.Document(src);
                if (doc == null) throw new Exception("Word文件无效或者Word文件被加密！");

                int maxHeadLevel = 0;
                foreach (Aspose.Words.Paragraph para in doc.GetChildNodes(NodeType.Paragraph, true))
                {
                    if (para.ParagraphFormat.IsHeading)
                    {
                        var headLevel = para.ListFormat.ListLevelNumber + 1;
                        if (headLevel > maxHeadLevel)
                        {
                            maxHeadLevel = headLevel;
                        }
                    }
                }

                Aspose.Words.Saving.PdfSaveOptions saveOption = new Aspose.Words.Saving.PdfSaveOptions();
                //HeadingsOutlineLevels最大可以设置为8
                if (maxHeadLevel > 8)
                {
                    maxHeadLevel = 8;
                }
                saveOption.OutlineOptions.HeadingsOutlineLevels = maxHeadLevel;
                doc.Save(dest, saveOption);
            }
            catch (Aspose.Words.IncorrectPasswordException ie)
            {
                throw new Exception("有密码!");
            }
            catch (Aspose.Words.UnsupportedFileFormatException ufe)
            {
                throw new Exception(string.Format("文件格式无法识别! {0}", ufe.Message));
            }
            catch (Aspose.Words.FileCorruptedException fce)
            {
                throw new Exception(string.Format("文件损坏! {0}", fce.Message));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Word转成Html
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="htmlFilePath">转档文件</param>
        public static void WordConvertToHtml(string sourceFilePath, string htmlFilePath)
        {
            CheckWordLic();
            // open word file
            var doc = new Aspose.Words.Document(sourceFilePath);
            // validate parameter
            if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密！"); }
            doc.Save(htmlFilePath, Aspose.Words.SaveFormat.Html);
        }

        /// <summary>
        /// Excel转成Pdf
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">转档文件</param>
        public static void ExcelConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            InnerExcelConvertToPdf(sourceFilePath, pdfFilePath);
        }

        /// <summary>
        /// Excel转成Pdf
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">转档文件</param>
        /// <param name="maxRow">检查最大行数成一页</param>
        public static void ExcelConvertToPdf(string sourceFilePath, string pdfFilePath, int maxRow)
        {
            InnerExcelConvertToPdf(sourceFilePath, pdfFilePath, maxRow);
            /*
            CheckExcelLic();
            var excel = new Aspose.Cells.Workbook(sourceFilePath);
            try
            {
                bool greaterMax = false;
                if (maxRow <= 0) { maxRow = 10; }
                //设置页
                if (excel.Worksheets.Count > 0)
                    for (var n = 0; n < excel.Worksheets.Count; n++)
                    {
                        //var sheet = excel.Worksheets[n + 1];
                        var sheet = excel.Worksheets[n];
                        //if (sheet == null || (maxRow > 0 && sheet.Cells.MaxDataRow > maxRow)) continue;
                        sheet.PageSetup.Zoom = 100;
                        //纵向|横向
                        sheet.PageSetup.Orientation = Aspose.Cells.PageOrientationType.Portrait;
                        //sheet.AutoFitColumns(new Aspose.Cells.AutoFitterOptions());
                        //sheet.PageSetup.FitToPagesTall = 1;
                        sheet.PageSetup.FitToPagesWide = 1;
                        if (sheet == null || (maxRow > 0 && sheet.Cells.MaxDataRow > maxRow)) continue;
                        sheet.PageSetup.FitToPagesTall = 1;
                    }
            }
            catch { }
            //var opt = new Aspose.Cells.PdfSaveOptions(Aspose.Cells.SaveFormat.Pdf);
            //opt.PdfCompression = Aspose.Cells.Rendering.PdfCompressionCore.Lzw;
            //excel.Save(pdfFilePath, opt);
            excel.Save(pdfFilePath, Aspose.Cells.SaveFormat.Pdf);
            */
        }

        /// <summary>
        /// 内部Excel转成PDF文件
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="pdfFilePath"></param>
        private static void InnerExcelConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            CheckExcelLic();
            try
            {
                Aspose.Cells.Workbook excel = null;
                Aspose.Cells.LoadOptions loadOption = null;
                if (!string.IsNullOrEmpty(sourceFilePath) && Path.GetExtension(sourceFilePath).ToLower() == ".csv")
                {
                    var txtOptions = new Aspose.Cells.TxtLoadOptions(LoadFormat.Auto);
                    txtOptions.IsMultiEncoded = true;  
                    var encoding1 = get_charset(sourceFilePath);
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    txtOptions.Encoding = Encoding.GetEncoding(encoding1);
                    loadOption = txtOptions;
                }
                if (loadOption != null)
                {
                    excel = new Aspose.Cells.Workbook(sourceFilePath, loadOption);
                }
                else
                {
                    excel = new Workbook(sourceFilePath);
                }
                try
                {
                    if (excel.Worksheets.Count > 0)
                        for (var n = 0; n < excel.Worksheets.Count; n++)
                        {
                            var sheet = excel.Worksheets[n];
                            sheet.AutoFitColumns();
                            Aspose.Cells.Cell lastCell = sheet.Cells[CellsHelper.CellIndexToName(sheet.Cells.MaxDataRow, sheet.Cells.MaxColumn)];
                            //有合并单元格的情况
                            if (lastCell.IsMerged)
                            {

                                Aspose.Cells.Range rng = lastCell.GetMergedRange();
                                int idxCol = lastCell.Column + rng.ColumnCount;
                                int idxRow = lastCell.Row + rng.RowCount;
                                string cellName = CellsHelper.CellIndexToName(idxRow, idxCol);
                                lastCell = sheet.Cells[cellName];

                            }
                            sheet.PageSetup.Orientation = Aspose.Cells.PageOrientationType.Portrait;
                            sheet.PageSetup.FitToPagesTall = 0;
                            sheet.PageSetup.FitToPagesWide = 1;
                            sheet.PageSetup.PrintArea = "A1:" + lastCell.Name;
                        }
                }
                catch { }
                Aspose.Cells.SaveOptions saveOptions = new PdfSaveOptions();

                if (excel != null) { excel.Save(pdfFilePath, Aspose.Cells.SaveFormat.Pdf); }

            }
            catch (Aspose.Cells.CellsException ce)
            {
                switch (ce.Code)
                {
                    case Aspose.Cells.ExceptionType.IncorrectPassword:
                        throw new Exception(string.Format("有密码!"));
                    case Aspose.Cells.ExceptionType.FileFormat:
                        throw new Exception(string.Format("无效的文件格式! {0}", ce.Message));
                    case Aspose.Cells.ExceptionType.UnsupportedFeature:
                        throw new Exception(string.Format("文档格式不支持! {0}", ce.Message));
                    case Aspose.Cells.ExceptionType.UnsupportedStream:
                        throw new Exception(string.Format("非法格式不正确的数据流! {0}", ce.Message));
                    default:
                        throw ce;
                }
                //throw new Exception(string.Format("有密码! {0}", ce.ToString()), ce);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 内部Excel转成PDF文件
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">目标文件</param>
        /// <param name="maxRow">最大行数</param>
        private static void InnerExcelConvertToPdf(string sourceFilePath, string pdfFilePath, int maxRow)
        {
            CheckExcelLic();
            int totalRow = 0;
            Aspose.Cells.Cell lastCell = null;
            try
            {
                Aspose.Cells.Workbook excel = null;
                excel = new Aspose.Cells.Workbook(sourceFilePath);
                try
                {

                    if (excel.Worksheets.Count > 0)
                        for (var n = 0; n < excel.Worksheets.Count; n++)
                        {
                            var sheet = excel.Worksheets[n];
                            sheet.AutoFitColumns();
                            if (sheet.Cells.MaxDataRow > 0 && sheet.Cells.MaxDataColumn > 0)
                            {
                                totalRow += sheet.Cells.MaxDataRow;
                                lastCell = sheet.Cells[
                                        CellsHelper.CellIndexToName(sheet.Cells.MaxDataRow,
                                            sheet.Cells.MaxColumn)];
                                //有合并单元格的情况
                                if (lastCell.IsMerged)
                                {

                                    Aspose.Cells.Range rng = lastCell.GetMergedRange();
                                    int idxCol = lastCell.Column + rng.ColumnCount;
                                    int idxRow = lastCell.Row + rng.RowCount;
                                    string cellName = CellsHelper.CellIndexToName(idxRow, idxCol);
                                    lastCell = sheet.Cells[cellName];

                                }
                                sheet.PageSetup.Orientation = Aspose.Cells.PageOrientationType.Portrait;
                                sheet.PageSetup.FitToPagesTall = 0;
                                sheet.PageSetup.FitToPagesWide = 1;

                                sheet.PageSetup.PrintArea = "A1:" + lastCell.Name;

                            }
                        }
                }
                catch (Exception ex)
                {

                }
                if (totalRow <= maxRow)
                {
                    if (excel != null) { excel.Save(pdfFilePath, Aspose.Cells.SaveFormat.Pdf); }
                }
                else
                {
                    throw new Exception("超出最大行数限制！");
                }
            }
            catch (Aspose.Cells.CellsException ce)
            {
                switch (ce.Code)
                {
                    case Aspose.Cells.ExceptionType.IncorrectPassword:
                        throw new Exception(string.Format("有密码!"));
                    case Aspose.Cells.ExceptionType.FileFormat:
                        throw new Exception(string.Format("无效的文件格式! {0}", ce.Message));
                    case Aspose.Cells.ExceptionType.UnsupportedFeature:
                        throw new Exception(string.Format("文档格式不支持! {0}", ce.Message));
                    case Aspose.Cells.ExceptionType.UnsupportedStream:
                        throw new Exception(string.Format("非法格式不正确的数据流! {0}", ce.Message));
                    default:
                        throw ce;
                }
                //throw new Exception(string.Format("有密码! {0}", ce.ToString()), ce);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static Encoding GetEncoding(string destPath)
        {
          
            using (StreamReader reader = new StreamReader(destPath))
            { 
                return reader.CurrentEncoding;
            }


        }

        private static string get_charset(string destPath) {
            string charset = "GBK";
            byte[] first3Bytes = new byte[3];
            try
            {
                bool check = false;
                using (FileStream reader = new FileStream(destPath, FileMode.Open))
                {
                    reader.Position = 0;
                    int read = reader.Read(first3Bytes, 0, 3);
                    if (read == -1)
                        return charset;
                    if (first3Bytes[0] == (byte)0xFF && first3Bytes[1] == (byte)0xFE)
                    {
                        charset = "UTF-16LE";
                        check = true;
                    }
                    else if (first3Bytes[0] == (byte)0xFE
                          && first3Bytes[1] == (byte)0xFF)
                    {
                        charset = "UTF-16BE";
                        check = true;
                    }
                    else if (first3Bytes[0] == (byte)0xEF
                          && first3Bytes[1] == (byte)0xBB
                          && first3Bytes[2] == (byte)0xBF)
                    {
                        charset = "UTF-8";
                        check = true;
                    }
                    reader.Position = 0;
                    if (!check)
                    {
                        while ((read = reader.ReadByte()) != -1)
                        {
                            if (read >= 0xF0)
                                break;
                            if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的，也算是GBK
                                break;
                            if (0xC0 <= read && read <= 0xDF)
                            {
                                read = reader.ReadByte();
                                if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)
                                                                  // (0x80
                                                                  // - 0xBF),也可能在GB编码内
                                    continue;
                                else
                                    break;
                            }
                            else if (0xE0 <= read && read <= 0xEF)
                            {// 也有可能出错，但是几率较小
                                read = reader.ReadByte();
                                if (0x80 <= read && read <= 0xBF)
                                {
                                    read = reader.ReadByte();
                                    if (0x80 <= read && read <= 0xBF)
                                    {
                                        charset = "UTF-8";
                                        break;
                                    }
                                    else
                                        break;
                                }
                                else
                                    break;
                            }
                        }
                    }
                } 
            } 
            catch (Exception e)
            {

            }
            finally
            {

            }
            return charset;
        }


        /// <summary>
        /// Excel转成Html
        /// </summary>
        /// <param name="src">源文件</param>
        /// <param name="dest">转档文件</param>
        public static void ExcelConvertToHtml(string src, string dest)
        {
            CheckExcelLic(); 
            if (!string.IsNullOrEmpty(src) && Path.GetExtension(src).ToLower() == ".csv")
            {
                var txtOptions = new Aspose.Cells.TxtLoadOptions(LoadFormat.Auto); 
                txtOptions.IsMultiEncoded = true;
                var encoding1 = get_charset(src);
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                txtOptions.Encoding = Encoding.GetEncoding(encoding1);
                using (var workbook = new Aspose.Cells.Workbook(src, txtOptions))
                {
                    workbook.Save(dest, Aspose.Cells.SaveFormat.Html);
                }
            }
            //if (loadOption != null)
            //{
            //    excel = new Aspose.Cells.Workbook(src, loadOption);
            //    AutoFitterOptions autoFitterOptions = new AutoFitterOptions();
            //    autoFitterOptions.AutoFitMergedCells = true;
            //    foreach (var sheet in excel.Worksheets)
            //    {
            //        sheet.AutoFitColumns();
            //        //for (int i = 0; i < sheet.Cells.MaxDataColumn; i++)
            //        //{
            //        //    var columnWidth = sheet.Cells.GetColumnWidth(i);
            //        //    sheet.Cells.SetColumnWidth(i, columnWidth + 20);
            //        //}
            //    }
            //}
            else
            {
                using (var excel = new Workbook(src))
                {
                    foreach (var sheet in excel.Worksheets)
                    {
                        sheet.AutoFitColumns();
                    }
                    Aspose.Cells.HtmlSaveOptions saveOption = new HtmlSaveOptions();
                    //saveOption.ExportHiddenWorksheet = false;
                    saveOption.LinkTargetType = HtmlLinkTargetType.Self;
                    //saveOption.Encoding = Encoding;
                    excel.Save(dest, saveOption); 
                    // FrSheetHandler(dest); 
                }
            }
           
        }
         

        private static void FrSheetHandler(string src)
        {
            const string original = "frSheet";
            var dest = $"frSheet_{Guid.NewGuid():N}";
            ReplaceInFile(src, original, dest);

            var subFileDir = src.Replace(Path.GetExtension(src), "_files");
            if (!Directory.Exists(subFileDir)) return;
            Directory.GetFiles(subFileDir).Where(sub => sub.EndsWith(".htm"))
                .AsParallel().ForAll(sub => ReplaceInFile(sub, original, dest));
        }

        private static void ReplaceInFile(string target, string original, string dest)
        {
            if (!File.Exists(target)) return;
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding encoding = Encoding.GetEncoding("gb2312");
            var reader = new StreamReader(target, encoding);
            var content = reader.ReadToEnd();
            reader.Close();
            content = content.Replace(original, dest);
            var writer = new StreamWriter(target, false, encoding);
            writer.Write(content);
            writer.Close();
        }

        /// <summary>
        /// Ppt转成Pdf
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">转档文件</param>
        public static void PptConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            try
            {
                CheckPptLic();

                var loadOptions = new LoadOptions { DefaultAsianFont = "微软雅黑" };

                Presentation pre = new Presentation(sourceFilePath, loadOptions);
                pre.Save(pdfFilePath, Aspose.Slides.Export.SaveFormat.Pdf);
                pre.Dispose();
            }
            catch (Aspose.Slides.PptxCorruptFileException cfex)
            {
                throw new Exception(string.Format("文件损坏! {0}", cfex.Message));
            }
            catch (Aspose.Slides.PptCorruptFileException cfe)
            {
                throw new Exception(string.Format("文件损坏! {0}", cfe.Message));
            }
            catch (Aspose.Slides.PptxUnsupportedFormatException fex)
            {
                if (fex.Message.IndexOf("Encrypted presentations are not supported", StringComparison.Ordinal) >= 0)
                {
                    throw new Exception("有密码!");
                }
                else
                {
                    throw new Exception(string.Format("文件格式无法识别! {0}", fex.Message));
                }
            }
            catch (Aspose.Slides.PptUnsupportedFormatException fe)
            {
                if (fe.Message.IndexOf("Encrypted presentations are not supported", StringComparison.Ordinal) >= 0)
                {
                    throw new Exception("有密码!");
                }
                else
                {
                    throw new Exception(string.Format("文件格式无法识别! {0}", fe.Message));
                }
            }
            catch (Aspose.Slides.PptxReadException prex)
            {
                throw new Exception(string.Format("文件读取错误! {0}", prex.Message));
            }
            catch (Aspose.Slides.PptReadException pre)
            {
                throw new Exception(string.Format("文件读取错误! {0}", pre.Message));
            }
            catch (Aspose.Slides.InvalidPasswordException ie)
            {
                throw new Exception("有密码");
            }
            catch (Exception ex)
            {
                throw ex;
            }
            /*
            if (".ppt".Equals(System.IO.Path.GetExtension(sourceFilePath), StringComparison.CurrentCultureIgnoreCase))
                new Aspose.Slides.Presentation(sourceFilePath).Save(pdfFilePath, Aspose.Slides.Export.SaveFormat.Pdf);
            else
                new Aspose.Slides.Pptx.PresentationEx(sourceFilePath).Save(pdfFilePath,
                                                                           Aspose.Slides.Export.SaveFormat.Pdf);
             */
        }

        /// <summary>
        /// Ppt转成Html
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="htmlFilePath">转档文件</param>
        public static void PptConvertToHtml(string sourceFilePath, string htmlFilePath)
        {
            CheckPptLic();
            Presentation pre = new Presentation(sourceFilePath);
            pre.Save(htmlFilePath, Aspose.Slides.Export.SaveFormat.Html);
        }

        /// <summary>
        /// Msg转换成Eml
        /// </summary>
        /// <param name="msgFilePath"></param>
        /// <param name="emlFilePath"></param>
        public static void MsgConvertToEml(string msgFilePath, string emlFilePath)
        {
            CheckEmailLic();
            var msg = Aspose.Email.MailMessage.Load(msgFilePath);
            Aspose.Email.SaveOptions saveOptions = new Aspose.Email.EmlSaveOptions(Aspose.Email.MailMessageSaveType.EmlFormat);
            msg.Save(emlFilePath, saveOptions);
        }


        public static void EmailConvertToHtml(string msgFilePath, string htmlFilePath)
        {
            CheckEmailLic();
            var msg = Aspose.Email.MailMessage.Load(msgFilePath);
            var options = Aspose.Email.SaveOptions.DefaultHtml;

            var attachmentdir = Path.Combine(Path.GetDirectoryName(msgFilePath), "attachments");

            if (!Directory.Exists(attachmentdir))
            {
                Directory.CreateDirectory(attachmentdir);
            }

            string subDesName = Path.GetFileNameWithoutExtension(htmlFilePath);
            var attachmentSubDir = Path.Combine(attachmentdir, subDesName);
            int i = 0;

            foreach (Aspose.Email.Attachment attachment in msg.Attachments)
            {
                // To display the the attachment file name
                // Save the attachment to disc
                // You can also save the attachment to memory stream
                i++;
                if (!Directory.Exists(attachmentSubDir))
                {
                    Directory.CreateDirectory(attachmentSubDir);
                }
                var aPath = Path.Combine(attachmentSubDir, i + "_" + attachment.Name.Trim());
                attachment.Save(aPath);
            }
            options.HtmlFormatOptions = Aspose.Email.HtmlFormatOptions.WriteCompleteEmailAddress;
            msg.BodyEncoding = Encoding.UTF8;
            msg.Save(htmlFilePath, options);
            EmlHtmFileFormart(htmlFilePath, msg);
        }

        public static string dateToWeek(DateTime datetime)
        {
            string[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return weekDays[(int)datetime.DayOfWeek];
        }

        private static void EmlHtmFileFormart(string htmlFilePath, Aspose.Email.MailMessage msg)
        {

            string strHtml = "";
            strHtml += "<html><head><title></title>";
            strHtml += "</head><body style=\"margin:0 0;font-family: arial; \">";
            strHtml += "<div>";
            strHtml += "<div style=\"background-color:#f5f5f5;padding:20px 10px 5px 20px;\">";
            string subject = "No Subject";
            if (!string.IsNullOrWhiteSpace(msg.Subject))
            {
                subject = msg.Subject;
            }
            strHtml += "<div style=\"font-weight:bold;font-size:14px;\">" + subject + "</div>";

            strHtml += "<div style=\"font-size:12px;line-height:18px;color:#666666;\">";
            strHtml += "<label style=\"float:left;\">发件人：</label>";
            if (string.IsNullOrWhiteSpace(msg.From.DisplayName))
            {
                strHtml += "<div style=\"color:#666666\">&quot;<span style=\"color:#333333\">" + msg.From.Address + "</span>&quot;&nbsp; &lt;" + msg.From.Address + "&gt;</div></div>";
            }
            else
            {
                strHtml += "<div style=\"color:#666666\">&quot;<span style=\"color:#333333\">" + msg.From.DisplayName + "</span>&quot;&nbsp; &lt;" + msg.From.Address + "&gt;</div></div>";
            }

            string strSendTime = msg.Date.ToString("yyyy-MM-dd HH:mm:ss");
            string strWeek = dateToWeek(msg.Date);
            string strDate = msg.Date.ToString("yyyy年MM月dd日");
            string strTime = msg.Date.ToString("HH:mm:ss");

            strHtml += "<div style=\"font-size:12px;line-height:18px;color:#666666;\">";
            strHtml += "<label style=\"float:left;\">时&nbsp;&nbsp;&nbsp;&nbsp;间：</label>";
            strHtml += "<div style=\"\" title=\"" + strSendTime + "\">" + strDate + "(" + strWeek + ")" + "&nbsp;&nbsp;" + strTime + "</div></div>";

            strHtml += "<div style=\"font-size:12px;line-height:18px;color:#666666;\">";
            strHtml += "<div style=\"float:left\">";
            strHtml += "<label>收件人：</label>";
            strHtml += "</div>";
            //strHtml += "<div style=\"\">" + msg.getTo().Replace("<", "&lt").Replace(">", "&gt") + "</div></div>";
            strHtml += "<div style=\"float:left;width:80%;\">";
            if (msg.To.Count > 0)
            {
                for (int i = 0; i < msg.To.Count; i++)
                {
                    if (msg.To[i].DisplayName == "")
                    {
                        strHtml += "<div style=\"float: left;padding-right: 10px;\">&quot;<span style=\"color:#333333\">" + msg.To[i].Address + "</span>&quot; &nbsp;&lt;" + msg.To[i].Address + "&gt;;</div>";
                    }
                    else
                    {
                        strHtml += "<div style=\"float: left;padding-right: 10px;\">&quot;<span style=\"color:#333333\">" + msg.To[i].DisplayName + "</span>&quot; &nbsp;&lt;" + msg.To[i].Address + "&gt;;</div>";
                    }

                }
            }
            strHtml += "<div style=\"clear: both;\"></div>";
            strHtml += "</div>";
            strHtml += "<div style=\"clear: both;\"></div>";
            strHtml += "</div>";


            if (msg.CC.Count > 0)
            {
                strHtml += "<div style=\"font-size:12px;line-height:18px;color:#666666;\">";
                strHtml += "<div style=\"float:left\">";
                strHtml += "<label>抄&nbsp;&nbsp;&nbsp;&nbsp;送：</label>";
                strHtml += "</div>";
                strHtml += "<div style=\"float:left;width:80%;\">";
                for (int i = 0; i < msg.CC.Count; i++)
                {
                    if (msg.CC[i].DisplayName == "")
                    {
                        strHtml += "<div style=\"float:left;padding-right: 10px;\">&quot;<span style=\"color:#333333\">" + msg.CC[i].Address + "</span>&quot;&nbsp; &lt;" + msg.CC[i].Address + "&gt;;</div>";
                    }
                    else
                    {
                        strHtml += "<div style=\"float:left;padding-right: 10px;\">&quot;<span style=\"color:#333333\">" + msg.CC[i].DisplayName + "</span>&quot;&nbsp; &lt;" + msg.CC[i].Address + "&gt;;</div>";
                    }

                }
                strHtml += "<div style=\"clear: both;\"></div>";
                strHtml += "</div>";
                strHtml += "<div style=\"clear: both;\"></div>";
                strHtml += "</div>";
            }

            strHtml += "</div>";
            if (msg.Attachments.Count > 0)
            {
                strHtml += "<div style=\"min-height:30px;background-color:#eeeeee;border-bottom:1px solid #d0d4d9\">";
                int n = 0;
                for (int i = 0; i < msg.Attachments.Count; i++)
                {
                    n++;
                    strHtml += "<div class=\"attachmentsEl\" style=\"float: left;font-size: 12px;color: #48515d;padding-left: 10px;padding-right: 10px;padding-top: 8px;padding-bottom: 8px;\">" + n + "_" + msg.Attachments[i].Name + "</div>";
                }
                strHtml += "<div style=\"clear: both;\"></div>";
                strHtml += "</div>";
            }


            try
            {
                strHtml += "<div style=\"margin-left:20px;\">" + File.ReadAllText(htmlFilePath, Encoding.UTF8) + "</div>";

                File.WriteAllText(htmlFilePath, strHtml, Encoding.UTF8);

            }
            catch (Exception e)
            {
                throw e;
            }

        }


        /// <summary>
        /// Project转换成Pdf
        /// </summary>
        /// <param name="projectFilePath">project格式文件地址</param>
        /// <param name="pdfFilePath">转换后的pdf存放地址</param>
        public static void ProjectConvertToPdf(string projectFilePath, string pdfFilePath)
        {
            CheckTasksLic();
            Project project = new Project(projectFilePath);
            project.Save(pdfFilePath, Aspose.Tasks.Saving.SaveFileFormat.PDF);
        }

        /// <summary>
        /// Project转换成图片
        /// </summary>
        /// <param name="projectFilePath">project格式文件地址</param>
        /// <param name="pdfFilePath">转换后的pdf存放地址</param>
        public static void ProjectToOneBitmap(string projectFilePath, string objectFilePath)
        {
            CheckTasksLic();
            var project = new Project(projectFilePath);
            // create ImageSaveOptions with desired format
            var options = new Aspose.Tasks.Saving.ImageSaveOptions(Aspose.Tasks.Saving.SaveFileFormat.JPEG);
            // render project data to image format
            project.Save(objectFilePath, options);
        }

        public static void VisioToOneBitmap(string visioFilePath, string objectFilePath)
        {
            CheckDiagramLic();
            var diagram = new Aspose.Diagram.Diagram(visioFilePath);
            diagram.Save(objectFilePath, Aspose.Diagram.SaveFileFormat.JPEG);
        }



        /// <summary>
        /// visio转换成Pdf
        /// </summary>
        /// <param name="visioFilePath">visio文件地址</param>
        /// <param name="pdfFilePath">转换后的pdf存放地址</param>
        public static void VisioConvertToPdf(string visioFilePath, string pdfFilePath)
        {
            CheckDiagramLic();
            Diagram diagram = new Diagram(visioFilePath);
            diagram.Save(pdfFilePath, Aspose.Diagram.SaveFileFormat.PDF);
        }

        /// <summary>
        /// Word文件转换一页图片
        /// </summary>
        /// <param name="sourceFilePath">文件路径</param>
        /// <param name="imageFilePath">缩略图路径</param>
        /// <param name="resolution">分辨率</param>
        public static void WordToOneBitmap(string sourceFilePath, string imageFilePath, float resolution = 300f)
        {
            CheckWordLic();
            // open word file
            var doc = new Aspose.Words.Document(sourceFilePath);
            // validate parameter
            if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密！"); }
            if (resolution <= 0.0) { resolution = 128f; }
            var imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Jpeg);
            imageSaveOptions.PageIndex = 0;
            //imageSaveOptions.PageSet= new Aspose.Words.Saving.PageSet(0);
            doc.Save(imageFilePath, imageSaveOptions);
        }

        /// <summary>
        /// Excel文件转换一页图片
        /// </summary>
        /// <param name="sourceFilePath">文件路径</param>
        /// <param name="imageFilePath">缩略图路径</param>
        /// <param name="resolution">分辨率</param>
        public static void ExcelToOneBitmap(string sourceFilePath, string imageFilePath, float resolution = 300f)
        {
            Aspose.Cells.Workbook workbook = null;
            try
            {
                CheckExcelLic();
                workbook = new Aspose.Cells.Workbook(sourceFilePath);
                if (workbook == null) { throw new Exception("Excel文件无效或者Excel文件被加密！"); }
                foreach (Aspose.Cells.Worksheet worksheet in (Aspose.Cells.CollectionBase<Aspose.Cells.Worksheet>)workbook.Worksheets)
                {
                    worksheet.PageSetup.LeftMargin = 0.0;
                    worksheet.PageSetup.RightMargin = 0.0;
                    worksheet.PageSetup.BottomMargin = 0.0;
                    worksheet.PageSetup.TopMargin = 0.0;
                    var sheetRender = new Aspose.Cells.Rendering.SheetRender(worksheet, new Aspose.Cells.Rendering.ImageOrPrintOptions()
                    {
                        ImageType = Aspose.Cells.Drawing.ImageType.Jpeg,
                        OnePagePerSheet = true,
                        PrintingPage = Aspose.Cells.PrintingPageType.IgnoreBlank
                    });
                    if (sheetRender.PageCount <= 0) continue;
                    sheetRender.ToImage(0, imageFilePath);
                    break;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 图片转成Jpeg
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="outFilePath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void AsposeImageConvertToJpeg(string sourceFilePath, string outFilePath, int width, int height)
        {
            CheckImageLic();
            //for (var n = 0; n < 3; n++)
            //{
            //	if (Aspose.Imaging.Image.CanLoad(sourceFilePath))
            //		break;
            //	Thread.Sleep(3000);
            //}
            var image = Aspose.Imaging.Image.Load(sourceFilePath);
            if (width > 0 && height > 0)
            {
                if (image.Width > width && image.Height > height)
                {
                    double newWidth = image.Width;
                    double newHeight = image.Height;
                    if (image.Width > image.Height || image.Width == image.Height)
                    {
                        if (image.Width > width)
                        {
                            newWidth = width;
                            newHeight = image.Height * (width / image.Width);
                        }
                    }
                    else
                    {
                        if (image.Height > height)
                        {
                            newHeight = height;
                            newWidth = image.Width * (height / image.Height);
                        }
                    }
                    image.Resize((int)newWidth, (int)newHeight);
                }
            }
            image.Save(outFilePath, new Aspose.Imaging.ImageOptions.JpegOptions());
            image = null;
        }

        /// <summary>
        ///  图片转档 生成转档原图
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="outFilePath"></param>
        /// <param name="CompressionType"></param>
        public static void AsposeImageConvertToJpeg(string sourceFilePath, string outFilePath)
        {
            CheckImageLic();
            var ext = Path.GetExtension(sourceFilePath);
            ext = string.IsNullOrEmpty(ext) ? string.Empty : ext.ToLower();
            if (ext == ".psd")
            {
                CheckPsdLic();
                using (var image = Aspose.PSD.Image.Load(sourceFilePath))
                {
                    image.Save(outFilePath, new Aspose.PSD.ImageOptions.JpegOptions());
                }
            }
            else
            {
                using (var image = Aspose.Imaging.Image.Load(sourceFilePath))
                {
                    image.Save(outFilePath, new Aspose.Imaging.ImageOptions.JpegOptions());
                }
            }
        }


        /// <summary>
        /// 图片转成图片
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="output"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        public static void AsposeImageConvertToImage(Stream stream, string output, int w, int h)
        {
            Aspose.Imaging.Image image = null;
            try
            {
                CheckImageLic();
                image = Aspose.Imaging.Image.Load(stream);
                AsposeImageConvertToImage(image, output, w, h);
            }
            finally
            {
                try { if (image != null) { image.Dispose(); } }
                catch { }
                image = null;
            }
        }

        /// <summary>
        /// 图片转成图片
        /// </summary>
        /// <param name="source"></param>
        /// <param name="dest"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        public static void AsposeImageConvertToImage(string source, string dest, int w, int h)
        {
            Aspose.Imaging.Image image = null;
            try
            {
                CheckImageLic();
                image = Aspose.Imaging.Image.Load(source);
                AsposeImageConvertToImage(image, dest, w, h);
            }
            finally
            {
                try { if (image != null) { image.Dispose(); } }
                catch { }
                image = null;
            }

            #region 参考代码
            //Aspose.Imaging.Image image = null;
            //try
            //{
            //	CheckImageLic();
            //	//for (var n = 0; n < 3; n++)
            //	//{
            //	//	if (Aspose.Imaging.Image.CanLoad(sourceFilePath))
            //	//		break;
            //	//	Thread.Sleep(3000);
            //	//}
            //	WriteLog("load start");
            //	var ss = File.ReadAllBytes(sourceFilePath);
            //	WriteLog("load end"+ss.Length.ToString());
            //	var rs = new MemoryStream(ss);

            //	image = Aspose.Imaging.Image.Load(rs);
            //	if (width > 0 && height > 0)
            //	{
            //		if (image.Width > width && image.Height > height)
            //		{
            //			double newWidth = image.Width;
            //			double newHeight = image.Height;
            //			if (image.Width > image.Height || image.Width == image.Height)
            //			{
            //				if (image.Width > width)
            //				{
            //					newWidth = width;
            //					newHeight = image.Height*(width/image.Width);
            //				}
            //			} else
            //			{
            //				if (image.Height > height)
            //				{
            //					newHeight = height;
            //					newWidth = image.Width*(height/image.Height);
            //				}
            //			}
            //			image.Resize((int) newWidth, (int) newHeight);
            //		}
            //	}
            //	image.Save(outFilePath);
            //} finally
            //{
            //	try { if (image != null) { image.Dispose(); } }
            //	catch { }
            //	image = null;
            //}
            #endregion
        }


        public static void CadConvertTpPdf(string sourceFilePath, string objectFilePath)
        {
            CheckCadLic();
            using (var image = Aspose.CAD.Image.Load(sourceFilePath))
            {
                Aspose.CAD.ImageOptions.CadRasterizationOptions rasterizationOptions = new Aspose.CAD.ImageOptions.CadRasterizationOptions();
                rasterizationOptions.PageSize = new Aspose.CAD.SizeF(image.Width, image.Height);
                rasterizationOptions.Layouts = (new string[] { "Model" });
                // save PDF
                var pdfOptions = new Aspose.CAD.ImageOptions.PdfOptions();
                pdfOptions.VectorRasterizationOptions = rasterizationOptions;
                image.Save(objectFilePath, pdfOptions);
            }
        }

        public static void CadToOneBitmap(string sourceFilePath, string objectFilePath)
        {
            CheckCadLic();
            using (var image = Aspose.CAD.Image.Load(sourceFilePath))
            {

                // Create an instance of CadRasterizationOptions
                var rasterizationOptions = new Aspose.CAD.ImageOptions.CadRasterizationOptions();
                // Set page width & height

                int sizeNum = image.Width / 500;

                rasterizationOptions.PageWidth = (image.Width / sizeNum);
                rasterizationOptions.PageHeight = (image.Height / sizeNum);

                var options = new Aspose.CAD.ImageOptions.JpegOptions();
                options.VectorRasterizationOptions = rasterizationOptions;
                image.Save(objectFilePath, options);
            }
        }



        public static void CompressImage(Stream stream, string output, long quality, int w, int h)
        {
            using (var img = System.Drawing.Image.FromStream(stream))
            {
                var encoder = GetEncoder(img.RawFormat);
                if (encoder == null) return;

                var qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
                var encoderParams = new EncoderParameters(1);
                var encoderParam = new EncoderParameter(qualityEncoder, quality);
                encoderParams.Param[0] = encoderParam;

                var callback = new System.Drawing.Image.GetThumbnailImageAbort(() => false);
                using (var bitmap = img.GetThumbnailImage(w, h, callback, IntPtr.Zero))
                {
                    var graphics = Graphics.FromImage(bitmap);
                    graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphics.Clear(System.Drawing.Color.Transparent);
                    graphics.DrawImage(img, new System.Drawing.Rectangle(0, 0, w, h), new System.Drawing.Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
                    bitmap.Save(output, encoder, encoderParams);

                    encoderParams.Dispose();
                    encoderParam.Dispose();
                }
            }
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            var codecs = ImageCodecInfo.GetImageDecoders();
            foreach (var codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                    return codec;
            }
            return null;
        }

        private static void AsposeImageConvertToImage(Aspose.Imaging.Image image, string outFilePath, int width, int height)
        {
            if (image == null) return;
            if (width > 0 && height > 0)
            {
                if (image.Width > width && image.Height > height)
                {
                    double newWidth = image.Width;
                    double newHeight = image.Height;
                    if (image.Width > image.Height || image.Width == image.Height)
                    {
                        if (image.Width > width)
                        {
                            newWidth = width;
                            newHeight = (double)image.Height * ((double)width / (double)image.Width);
                        }
                    }
                    else
                    {
                        if (image.Height > height)
                        {
                            newHeight = height;
                            newWidth = (double)image.Width * ((double)height / (double)image.Height);
                        }
                    }
                    image.Resize((int)newWidth, (int)newHeight);
                }
            }
            Aspose.Imaging.ImageOptionsBase opt = new Aspose.Imaging.ImageOptions.JpegOptions();
            var ext = Path.GetExtension(outFilePath);
            ext = string.IsNullOrEmpty(ext) ? string.Empty : ext.ToLower();
            switch (ext)
            {
                case ".bmp":
                    opt = new Aspose.Imaging.ImageOptions.BmpOptions();
                    break;
                case ".gif":
                    opt = new Aspose.Imaging.ImageOptions.GifOptions();
                    break;
                case ".pdf":
                    opt = new Aspose.Imaging.ImageOptions.PdfOptions();
                    break;
                case ".png":
                    opt = new Aspose.Imaging.ImageOptions.PngOptions();
                    break;
                case ".psd":
                    opt = new Aspose.Imaging.ImageOptions.PsdOptions();
                    break;
                case ".tiff":
                case ".tif":
                    opt = new Aspose.Imaging.ImageOptions.TiffOptions(TiffExpectedFormat.Default);
                    break;
                default:
                    opt = new Aspose.Imaging.ImageOptions.JpegOptions();
                    break;
            }
            image.Save(outFilePath, opt);
        }


        public static void AsposeImageConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            CheckPdfLic();
            CheckImageLic();
            var extName = Path.GetExtension(sourceFilePath);
            var isChange = false;
            if (".tif".Equals(extName, StringComparison.OrdinalIgnoreCase) || ".tiff".Equals(extName, StringComparison.OrdinalIgnoreCase))
            {
                Aspose.Imaging.FileFormats.Tiff.TiffImage tif = null;
                try
                {
                    using (var img = Aspose.Imaging.Image.Load(sourceFilePath))
                    {
                        if (img is Aspose.Imaging.FileFormats.Tiff.TiffImage)
                        {
                            tif = (Aspose.Imaging.FileFormats.Tiff.TiffImage)img;
                            var fs = tif.Frames;

                            if (fs != null && fs.Length > 0)
                                foreach (var fr in fs)
                                {
                                    var w = fr.Size.Width;
                                    var h = fr.Size.Height;
                                    var max = w;
                                    var s = 1f;
                                    if (max < h) { max = h; }
                                    if (max > 9990)
                                    {
                                        s = 9990f / max;
                                        w = System.Convert.ToInt32(w * s);
                                        h = System.Convert.ToInt32(h * s);
                                        fr.Resize(w, h);
                                        isChange = true;
                                    }
                                }
                            if (isChange) { tif.Save(sourceFilePath, true); }

                        }
                        else
                        {
                            Console.WriteLine(string.Format("图片格式不正确{0}，不是tif文件", img.GetType().Name));
                            //throw new Exception(string.Format("图片格式不正确{0}", img.GetType().Name));
                        }
                    }
                }
                catch (Aspose.Imaging.CoreExceptions.CompressorException ce)
                {
                    throw new Exception(string.Format("压缩格式错误:{0}", ce.Message));
                }
                catch (Aspose.Imaging.CoreExceptions.FrameworkException fe)
                {
                    throw new Exception(string.Format("错误:{0}", fe.Message));
                }
                catch (Aspose.Imaging.CoreExceptions.ImageCreateException ice)
                {
                    throw new Exception(string.Format("图片创建错误:{0}", ice.Message));
                }
                catch (Aspose.Imaging.CoreExceptions.ImageLoadException ile)
                {
                    throw new Exception(string.Format("图片加载错误:{0}", ile.Message));
                }
                catch (Aspose.Imaging.CoreExceptions.ImageSaveException ise)
                {
                    throw new Exception(string.Format("图片保存错误:{0}", ise.Message));
                }
                catch (Aspose.Imaging.CoreExceptions.ImageException ie)
                {
                    throw new Exception(string.Format("错误:{0}", ie.Message));
                }
                finally
                {
                    try
                    {
                        if (tif != null) { tif.Dispose(); tif = null; }
                    }
                    catch { }
                }
            }

            using (Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document())
            {
                using (FileStream ffs = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] tmpBytes = new byte[ffs.Length];
                    ffs.Read(tmpBytes, 0, System.Convert.ToInt32(ffs.Length));

                    MemoryStream mystream = new MemoryStream(tmpBytes);
                    Bitmap b = new Bitmap(mystream);
                    //Create a new section in the Pdf document
                    Aspose.Pdf.Page page = pdfDoc.Pages.Add();

                    //Create an image object
                    Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();

                    //Add the image into paragraphs collection of the section
                    page.Paragraphs.Add(image1);

                    image1.ImageStream = mystream;

                    var ha = image1.FixHeight;
                    if (b.Width > b.Height)
                    {
                        // if the Image width is greater than page width, then set the page orientation to Landscape
                        page.PageInfo.IsLandscape = true;

                    }
                    else
                    {
                        // if the Image width is less than page width, then set the page orientation to Portrait
                        page.PageInfo.IsLandscape = false;
                    }
                    pdfDoc.Save(pdfFilePath);
                }
            }
        }

        public static void ImageConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            AsposeImageConvertToPdf(sourceFilePath, pdfFilePath);
        }


        /// <summary>
        /// Ppt转一页
        /// </summary>
        /// <param name="sourceFilePath">文件路径</param>
        /// <param name="imageFilePath">缩略图路径</param>
        /// <param name="resolution">分辨率</param>
        public static void PptToOneBitmap(string sourceFilePath, string imageFilePath, float resolution = 300f)
        {

            CheckPptLic();
            var ppt = new Aspose.Slides.Presentation(sourceFilePath);
            if (ppt == null) { throw new Exception("Ppt文件无效或者Ppt文件被加密！"); }
            var slide = ppt.Slides[0];
            slide.GetThumbnail(1f,1f).Save(imageFilePath, ImageFormat.Jpeg);
        }

        public static void ConvertPowerPointToImage(string powerPointInputPath, string imageOutputPath, string imageName, int startSlideNum, int endSlideNum, ImageFormat imageFormat)
        {
            Presentation presentation = new Presentation(powerPointInputPath);
            if (presentation == null) { throw new Exception("Ppt文件无效或者Ppt文件被加密！"); }
            if (imageOutputPath.Trim().Length == 0)
            {
                imageOutputPath = Path.GetDirectoryName(powerPointInputPath);
            }
            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }
            if (imageName.Trim().Length == 0)
            {
                imageName = Path.GetFileNameWithoutExtension(powerPointInputPath);
            }
            if (startSlideNum <= 0)
            {
                startSlideNum = 0;
            }
            if ((endSlideNum > presentation.Slides.Count) || (endSlideNum <= 0))
            {
                endSlideNum = presentation.Slides.Count;
            }
            if (startSlideNum > endSlideNum)
            {
                int num = startSlideNum;
                startSlideNum = endSlideNum;
                endSlideNum = startSlideNum;
            }
            if (imageFormat == null)
            {
                imageFormat = ImageFormat.Gif;
            }
            for (int i = startSlideNum; i <= endSlideNum; i++)
            {

                var slideByPosition = presentation.Slides[i];
                if (slideByPosition != null)
                {
                    MemoryStream stream = new MemoryStream();
                    slideByPosition.GetThumbnail(new Size(700, 0x20d)).Save(Path.Combine(imageOutputPath, imageName) + "_" + i.ToString() + "." + imageFormat.ToString(), ImageFormat.Jpeg);
                }
            }
        }

        /// <summary>
        /// Mht转成PDF文件
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">目标文件</param>
        public static void MhtConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            CheckPdfLic();
            var options = new Aspose.Pdf.MhtLoadOptions();
            // Load PDF document
            var document = new Aspose.Pdf.Document(sourceFilePath, options);
            // Save the output as PDF document
            document.Save(pdfFilePath);
        }

        /// <summary>
        /// Text转成PDF文件
        /// </summary>
        /// <param name="sourceFilePath">源文件</param>
        /// <param name="pdfFilePath">目标文件</param>
        public static void TextConvertToPdf(string sourceFilePath, string pdfFilePath)
        {
            CheckWordLic();
            var loadOption = new Aspose.Words.LoadOptions();
            loadOption.LoadFormat = Aspose.Words.LoadFormat.Text;
            var doc = new Aspose.Words.Document(sourceFilePath, loadOption);
            doc.Save(pdfFilePath, Aspose.Words.SaveFormat.Pdf);
        }

        /// <summary>
        /// Pdf文件转成svg格式
        /// </summary>
        /// <param name="pdfFilePath">Pdf文件路径</param>
        /// <param name="svgFilePath">生成的svg文件夹路径 a.svg 会生成目录</param>
        public static void PdfConvertToSvg(string pdfFilePath, string svgFilePath)
        {
            // Load PDF document
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document(pdfFilePath);
            // Instantiate an object of SvgSaveOptions
            Aspose.Pdf.SvgSaveOptions saveOptions = new Aspose.Pdf.SvgSaveOptions();
            // Do not compress SVG image to Zip archive
            saveOptions.CompressOutputToZipArchive = false;
            saveOptions.TreatTargetFileNameAsDirectory = true;
            // Resultant file name
            string outFileName = svgFilePath;
            // Save the output in SVG files
            doc.Save(outFileName, saveOptions);
        }

        /// <summary>
        /// pdf生成缩略图
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="imageFilePath"></param>
        public static void PdfToOneBitmap(string sourceFilePath, string imageFilePath)
        {
            CheckPdfLic();
            //定义Jpeg转换设备
            var document = new Aspose.Pdf.Document(sourceFilePath);
            //默认质量为100，设置质量的好坏与处理速度不成正比，甚至是设置的质量越低反而花的时间越长，怀疑处理过程是先生成高质量的再压缩
            var device = new Aspose.Pdf.Devices.JpegDevice();

            if (document.Pages.Count > 0)
            {
                using (var fs = new FileStream(imageFilePath, FileMode.OpenOrCreate))
                {
                    try
                    {
                        device.Process(document.Pages[1], fs);
                        fs.Close();
                    }
                    catch (Exception ex)
                    {
                        if (File.Exists(imageFilePath))
                        {
                            File.Delete(imageFilePath);
                        }
                        throw ex;
                    }
                }
            }
        }


        private static Aspose.Words.SaveFormat GetSaveFormat(ImageFormat imageFormat)
        {
            return !imageFormat.Equals((object)ImageFormat.Png) ? (!imageFormat.Equals((object)ImageFormat.Jpeg) ? (!imageFormat.Equals((object)ImageFormat.Tiff) ? (!imageFormat.Equals((object)ImageFormat.Bmp) ? Aspose.Words.SaveFormat.Unknown : Aspose.Words.SaveFormat.Bmp) : Aspose.Words.SaveFormat.Tiff) : Aspose.Words.SaveFormat.Jpeg) : Aspose.Words.SaveFormat.Png;
        }

        /// <summary>
        /// 如果pdf中图片尺寸过大，缩小图片尺寸
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="objectFilePath"></param>
        /// <param name="maxSize"></param>
        /// <returns></returns>
        public static bool FixPdf(string sourceFilePath, string objectFilePath, int maxSize = 13600)
        {
            CheckPdfLic();
            var result = false;
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document(sourceFilePath);

            // Create ImagePlacementAbsorber object to perform image placement search
            Aspose.Pdf.ImagePlacementAbsorber abs = new Aspose.Pdf.ImagePlacementAbsorber();

            // Accept the absorber for all the pages
            doc.Pages.Accept(abs);

            // Loop through all ImagePlacements, get image and ImagePlacement Properties
            foreach (Aspose.Pdf.ImagePlacement imagePlacement in abs.ImagePlacements)
            {
                // Get the image using ImagePlacement object
                Aspose.Pdf.XImage image = imagePlacement.Image;
                if (image.Height > maxSize || image.Width > maxSize)
                {
                    var pdfJpgLoadOption = new Aspose.Imaging.ImageLoadOptions.Jpeg2000LoadOptions();
                    MemoryStream pdfJpg = new MemoryStream();
                    image.Save(pdfJpg);
                    pdfJpg.Position = 0;
                    var imageStream = AsposeImageConvertToImage(Aspose.Imaging.Image.Load(pdfJpg, pdfJpgLoadOption), 13000, 13000);
                    if (imageStream != null)
                    {
                        using (imageStream)
                        {
                            imagePlacement.Page.Resources.Images.Replace(1, imageStream);

                        }
                    }
                    result = true;
                }
            }
            if (result)
            {
                doc.OptimizeResources(new Aspose.Pdf.Document.OptimizationOptions()
                {
                    LinkDuplcateStreams = true,
                    RemoveUnusedObjects = true,
                    RemoveUnusedStreams = true,
                    CompressImages = true,
                    ImageQuality = 10
                });
                doc.Save(objectFilePath);
            }
            return result;
        }

        private static Stream AsposeImageConvertToImage(Aspose.Imaging.Image image, int width, int height)
        {
            CheckImageLic();
            if (image == null) return null;
            MemoryStream result = new MemoryStream();
            using (image)
            {
                if (width > 0 && height > 0)
                {
                    if (image.Width > width || image.Height > height)
                    {
                        double newWidth = image.Width;
                        double newHeight = image.Height;
                        if (image.Width > image.Height || image.Width == image.Height)
                        {
                            if (image.Width > width)
                            {
                                newWidth = width;
                                newHeight = (double)image.Height * ((double)width / (double)image.Width);
                            }
                        }
                        else
                        {
                            if (image.Height > height)
                            {
                                newHeight = height;
                                newWidth = (double)image.Width * ((double)height / (double)image.Height);
                            }
                        }
                        image.Resize((int)newWidth, (int)newHeight);
                    }
                }
                Aspose.Imaging.ImageOptionsBase opt = new Aspose.Imaging.ImageOptions.JpegOptions();

                // Set the Compression to AdobeDeflate
                ///opt.Compression = TiffCompressions.Thunderscan;
                image.Save(result, opt);
            }
            result.Position = 0;
            return result;

        }


        /// <summary>
        /// 图片缩放
        /// </summary>
        /// <param name="image"></param>
        /// <param name="outFilePath"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void AsposeImageResize(Aspose.Imaging.Image image,int width, int height)
        {
            if (image == null) return;
            if (width > 0 && height > 0)
            {
                if (image.Width <= width && image.Height <= height)
                {
                    return;
                }

                double newWidth = image.Width;
                double newHeight = image.Height;
                if (image.Width > image.Height)//横向 按宽缩放
                {
                    if (image.Width > width)
                    {
                        newWidth = width;
                        newHeight = (double)image.Height * ((double)width / (double)image.Width);
                        image.Resize((int)newWidth, (int)newHeight);
                    }
                }
                else// 按高缩放
                {
                    if (image.Height > height)
                    {
                        newHeight = height;
                        newWidth = (double)image.Width * ((double)height / (double)image.Height);
                        image.Resize((int)newWidth, (int)newHeight);
                    }
                } 
            } 
        }
    }
}
